package com.shixj.easy.spider.executor;

import com.google.common.base.Strings;
import com.shixj.easy.spider.factory.DefaultCatalogFactory;
import com.shixj.easy.spider.factory.DefaultChapterFactory;
import com.shixj.easy.spider.factory.EntityFactory;
import com.shixj.easy.spider.model.Catalog;
import com.shixj.easy.spider.model.Chapter;
import com.shixj.easy.spider.model.RegexConfig;
import com.shixj.ef.config.FetchConfig;
import com.shixj.ef.core.HttpFetcher;
import com.shixj.ef.vo.FetchResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * Created by shixj on 2018/1/25.
 */
@Service("syncDefaultFetchExecutor")
@Slf4j
public class SyncDefaultFetchExecutor implements FetchExecutor {
    private RegexConfig regexConfig;
    private FetchConfig fetchConfig;

    /**
     * 获取小说
     */
    @Override
    public Catalog fetchNovel() {
        Catalog catalog = new Catalog();
        HttpFetcher fetcher = this.fetchConfig.start();
        FetchResult result = fetcher.getFetchResult();
        String url = result.getUrl();
        if (!Strings.isNullOrEmpty(url)) {
            if (url.matches(regexConfig.getNovelPageRegex())) {
                EntityFactory factory = new DefaultCatalogFactory();
                catalog = (Catalog) factory.build(result, regexConfig);
            }
        }
        return catalog;
    }

    /**
     * 获取章节
     */
    @Override
    public Chapter fetchChapter() {
        Chapter chapter = null;
        HttpFetcher fetcher = this.fetchConfig.start();
        FetchResult result = fetcher.getFetchResult();
        String url = result.getUrl();
        if (!Strings.isNullOrEmpty(url)) {
            if (url.matches(regexConfig.getChapterPageRegex())) {
                EntityFactory factory = new DefaultChapterFactory();
                chapter = (Chapter) factory.build(result, regexConfig);

            }
        }
        return chapter;
    }

    /**
     * 初始化爬虫解析执行器
     *
     * @param config
     * @return
     */
    @Override
    public FetchExecutor init(RegexConfig config) {
        this.regexConfig = config;
        this.fetchConfig = FetchConfig.bulid(regexConfig.getInitUrl()).setDepth(0).setMax(1)
                .setThreadLimit(1);
        return this;
    }
}
